﻿using System.Collections.Generic;
using StockEngine.Properties;
using StockModel;
using Utils;
using System.Linq;
using System;

namespace StockEngine.RealTime
{
    internal class AcquisitionEngine : TimeredEngineBase
    {
        #region Attributes

        private readonly List<EngineStockGroup> _groups;
    	private readonly GroupInitializer _initializer;
    	private readonly Acquisitor _acquisitor;

        #endregion

		#region Public Methods

		public AcquisitionEngine(List<EngineStockGroup> groups, GroupInitializer initializer, Acquisitor acquisitor) : base(Settings.Default.QuoteInterval, "Acquisition Engine")
        {
            _groups = groups;
			_initializer = initializer;
			_acquisitor = acquisitor;
        }

		public bool IsReadyToStop()
		{
			return _groups.All(g => !g.IsInitialized);
		}

		protected override void MainMethod()
        {
			IEnumerable<EngineStockGroup> uninitializedGroups = _groups.Where(g => !g.IsInitialized);

			foreach (EngineStockGroup engineStockGroup in uninitializedGroups)
			{
				if (_initializer.CanOpenGroup(engineStockGroup))
				{
					_initializer.OpenGroup(engineStockGroup);
				}
			}

			IEnumerable<EngineStockGroup> initializedGroups = _groups.Where(g => g.IsInitialized);

			foreach (EngineStockGroup engineStockGroup in initializedGroups)
			{
				if (!engineStockGroup.Market.IsOpen(DateTime.Now)) // Only de-initialize the group when we have collected a closed quotation
				{
					ObservableCollection2<StockGroupItem> items = engineStockGroup.Items.GetReadLock();
					try
					{
						if (items.Count > 0)
						{
							if (items.All(i => i.Item.QuotationCalendar.GetLatestAvailableDay().IsLastQuotationClosed() || engineStockGroup.RemovedItems.Contains(i)))
							{
								engineStockGroup.IsInitialized = false;
							}
						}
					}
					finally
					{
						engineStockGroup.Items.FreeReadLock();
					}
				}
			}

			_acquisitor.ProcessGroups();
        }

		#endregion
    }
}
